package com.tianpengtech.front.mobile.login;

import com.jfinal.aop.Before;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.tianpengtech.admin.dictionary.DictionaryDao;
import com.tianpengtech.common.model.dictionary.Dictionary;
import com.tianpengtech.common.model.fair.Fair;
import com.tianpengtech.common.model.moneylog.MoneyLog;
import com.tianpengtech.common.model.task.Task;
import com.tianpengtech.common.model.user.User;
import com.tianpengtech.front.mobile.common.constant.Constant;
import com.tianpengtech.front.mobile.common.util.R;
import com.tianpengtech.front.mobile.common.util.TokenUtil;
import com.tianpengtech.front.mobile.common.util.U;
import com.tianpengtech.front.mobile.common.util.UserUtil;
import com.tianpengtech.front.web.login.LoginService;
import com.tianpengtech.front.web.passport.PassportService;

import java.util.UUID;

/**
 * Created by ggd on 2017/7/17 0017.
 */
public class MobileLoginService {

	public static final MobileLoginService me = new MobileLoginService();
	private final LoginService loginService = LoginService.me;
	private final PassportService passportService = PassportService.me;
	private final User userDao = new User().dao();
	private DictionaryDao dictionaryDao = new DictionaryDao();
	// 用户密码错误次数 缓存key
	public static final String ERRORCOUNT_KEY = "error_count_";

	// 用户错误密码次数 缓存名称
	public static final String ERRORCOUNT_CACHENAME = "errorcount";

	public R login(String mobile, String password, String loginIp, String source) {

		if (!U.isMobile(mobile)) {
			return R.fail("手机号码格式不正确");
		}

		if (!U.isValidPass(password)) {
			return R.fail("密码只能是6-30个字符");
		}
		User user = loginService.findByMobile(mobile, User.USER_TYPE_FAIR);
		if (user == null) {
			return R.fail("当前用户不存在");
		}
		password = HashKit.sha256(user.getStr(User.SALT) + password);
//		password="c09e49c04eebbd9bada36f08203f6c03f1a216e023d30701d5861c24129a56d7";
		if (!password.equals(user.getStr(User.PASSWORD))) {
			return R.fail("用户名密码或密码不正确");
		}
		if (user.isStatusLockId()) {
			return R.fail("当前用户账号已被锁定");
		}
		R r = R.ok("恭喜你！注册成功");
		String token = TokenUtil.getToken();
		UserUtil.setCurrentUser(user, token, source);
		UserUtil.updateUserToken(token,user.getLong(User.ID));
		loginService.createLoginLog(user.getLong(User.ID), loginIp, "mobile");
		r.p("user", user);
		r.p("token", token);
		return r;
	}

	/**
	 * 登录
	 */
	public R register(String mobile, String password, int code, String loginIp, String source) throws Exception {
		try {
			try {
				if (!passportService.authCode(mobile, loginIp, code, true)) {
					return R.fail("验证码不正确");
				}
			} catch (Exception e) {
				e.printStackTrace();
				return R.fail("验证码不正确");
			}
			Ret r = passportService.reg(mobile, password, getCode(), User.USER_TYPE_FAIR);
			R result;
			if (r.isOk()) {
				result = login(mobile, password, loginIp, source);
			} else {
				result = R.fail(r.getStr("msg"));
			}
			return result;
		} catch (Exception e) {
			throw e;
		}

	}

	/**
	 * 退出登录
	 * 
	 * @param token
	 * @return
	 */
	public R logout(String token) {
		UserUtil.removeUser(token);
		return R.ok("退出成功");
	}

	/**
	 * 邀请注册
	 * 
	 * @return
	 */
	@Before(Tx.class)
	public R inviteReg(String code, String mobile, int authCode, String regIp) throws Exception {
		try {
			 try {
			 if(!passportService.authCode(mobile,regIp,authCode,true)){
			 return R.fail("验证码不正确");
			 }
			 }catch (Exception e){
			 e.printStackTrace();
			 return R.fail("验证码不正确");
			 }
			User user = loginService.findByMobile(mobile, User.USER_TYPE_FAIR);
			if (user == null) {
				Ret r = passportService.reg(mobile, Constant.DEFAULT_PASSWORD, getCode(), User.USER_TYPE_FAIR);
				if (r.isOk()) {
					long id = (long) r.get("id");
					
					user = loginService.findByMobile(mobile, User.USER_TYPE_FAIR);
					User ref = loginService.findByCode(code, User.USER_TYPE_FAIR);
					if (ref == null) {
						return R.fail("邀请码不存在");
					}
					user.set(User.REF_ID, ref.get(User.ID));
					user.set(User.CODE, getCode());
					user.update();
					Dictionary dict = dictionaryDao.readDirecotryByCode(300100);
					String val = null;
					if (dict == null) {
						val = "5";
					} else {
						val = dict.get(Dictionary.NAME, 5);
					}
					MoneyLog ml = new MoneyLog();
					ml.set(MoneyLog.WH_ID, ref.get(User.ID));
					ml.set(MoneyLog.OPERID, user.get(User.ID));
					ml.set(MoneyLog.STATE, MoneyLog.STATE_ADD);
					ml.set(MoneyLog.TYPE, MoneyLog.TYPE_YAOQING);
					ml.set(MoneyLog.MONEY, val);
					ml.set(MoneyLog.DESCRIPTION, "邀请好友获得奖励");
					ml.save();
					//Db.update("update fair_wh set money=money+"+val+" where mobile = ?",ref.getStr(User.MOBILE));
				} else {
					return R.fail("注册失败");
				}
			} else {
				return R.fail("当前手机账号已存在");
			}
			return R.ok("注册成功");
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * 生成邀请码
	 * 
	 * @return
	 */
	private String getCode() {
		return generateShortUuid();
	}

	private String[] chars = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o",
			"p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
			"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
			"V", "W", "X", "Y", "Z" };

	private String generateShortUuid() {
		StringBuffer shortBuffer = new StringBuffer();
		String uuid = UUID.randomUUID().toString().replace("-", "");
		for (int i = 0; i < 8; i++) {
			String str = uuid.substring(i * 4, i * 4 + 4);
			int x = Integer.parseInt(str, 16);
			shortBuffer.append(chars[x % 0x3E]);
		}
		return shortBuffer.toString();
	}
}
